<?php

class Maven_ManageCatalogSpr_Model_InsertProduct extends Varien_Object
{
	public $con;
	public $zipArray = array();
	public $fileArray = array();
	public $table_name = 'import_log_spr';
	public $logMsg = array();
	public $inStmt;
	public $upStmt;
	public $logFile;
	
	public $pricelogFile;
    public $mcId;
	public $logCheck = false;
	public $quickPrice = false;

	public function __construct()
	{
		$this->con = Mage::getSingleton('core/resource')->getConnection('core_write');
		$this->logFile = $this->getConfigVal('log_file');
       	$this->pricelogFile = $this->getPriceConfigVal('pricelog_file');
	}
	public function getConfigVal($field)
	{
		return Mage::getStoreConfig('managecatalogspr/price_file/'.$field);
	}
	public function cleanTempTable()
	{
	    $this->con->query("TRUNCATE TABLE $this->table_name");
	}
	public function cleanLog($flag=true)
	{  
		if($flag) {
			if(file_exists(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile)) {
				unlink(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile);
			}
		}
	}
	public function removeEtilizeProductAttribute()
	{

		/* @var Mage_Eav_Model_Mysql4_Entity_Attribute_Collection */
		$coll = Mage::getResourceModel('eav/entity_attribute_collection')
					//->
					;
		$collection = $product->getAttributes($groupId, false);
		foreach($collection as $attribute){
			//do something with the attribute
		}

		if ($id = $this->getRequest()->getParam('attribute_id')) {
			$model = Mage::getModel('catalog/resource_eav_attribute');
			// entity type check
			$model->load($id);
			if ($model->getEntityTypeId() != $this->_entityTypeId) {
				Mage::getSingleton('adminhtml/session')->addError(Mage::helper('catalog')->__('You cannot delete this attribute'));
				$this->_redirect('*/*/');
				return;
			}

			try {
				$model->delete();
			}catch (Exception $e) {



			}
		}
	}
	public function getLog()
	{
		$buffer='';
		if(file_exists(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile)) {
			$handle = fopen(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile, "r");
			if ($handle) {
				while (!feof($handle)) {
					$buffer .= "<BR/>".fgets($handle, 4096);
				}
				fclose($handle);
			}
		}
		return $buffer;
	}
	public function list_all_files($conn_id, $path){
	    
		$buff = ftp_nlist($conn_id, $path);
        ftp_pasv($conn_id,true);
		$final =  preg_grep('/.zip$/i',$buff);
       	$i =0;
		if($this->getPriceConfigVal){
			$fileSuffix= $this->getPriceConfigVal('file_suffix');
		}else{
			$fileSuffix=$this->getConfigVal('file_suffix');
		}
		$zipArray = array();
		foreach ($final as $val) {
			if(strstr($val,$fileSuffix)) {
				$ar = explode("/",$val);
				$zipArray[] = end($ar);
			}
		}
		return $zipArray;
	}

	public function downloadFiles()
	{
	   //$this->fileArray=array();
       //$this->fileArray[]= Maven_ManageCatalog_Model_Setting::getImportPath(Maven_ManageCatalog_Model_Setting::PRICE_FOLDER)."PRICECHG.TXT";
       
        $conn_id = ftp_connect($this->getConfigVal('price_file_url'));
        $login_result = ftp_login($conn_id, $this->getConfigVal('user') , $this->getConfigVal('password') );
        $Zips = $this->list_all_files($conn_id, $this->getConfigVal('price_file_ftp_path'));
       	foreach($Zips as $Zip) {
			if (ftp_get($conn_id, Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER).$Zip,
			$this->getConfigVal('price_file_ftp_path')."/".$Zip, FTP_BINARY)) {
			     if(PHP_OS == 'WINNT'){
			         $this->unzip1(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER).$Zip); 
    			    }else{
    			         $this->unzip(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER).$Zip);
    			    }
                
                				
				if(!$this->logCheck){
					Mage::log($Zip ." Downloaded Successfully ! ", 7, $this->logFile);
				}else{
					Mage::log($Zip ." Downloaded Successfully ! ", 7, $this->pricelogFile);
				}
			}else {
				if(!$this->logCheck){
					Mage::log($Zip ." Downloading Problem ! ", 7, $this->logFile);
				}else{
					Mage::log($Zip ." Downloading Problem ! ", 7, $this->pricelogFile);
				}
				
			}
		}
		ftp_close($conn_id);
        
	}
    
    public function unzip($src_file)
	{
	   
       	//$file_name = substr($src_file,0,-4).".TXT";
        $file_name=Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER).$this->getConfigVal('ftp_file');
		exec('cd '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER),$echoed);
		exec('unzip -o  ' . $src_file. ' -d '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER),$echoed);
        
        if(file_exists($file_name)){
       	  $this->fileArray[] = $file_name;
	    }else{
	      $this->fileArray[] = " ";
	    }
	}
    
    public function setFile($file_name)
	{
		$this->fileArray[] = $file_name;
	}
	
    	/**
	 * Unzip the source_file in the destination dir
	 * @Todo work only for the windows OS
	 * @param   string      The path to the ZIP-file.
	 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
	 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
	 * @param   boolean     Overwrite existing files (true) or not (false)
	 *
	 * @return  boolean     Succesful or not
	 */
	public function unzip1($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
	{
		if(function_exists("zip_open"))
		{
			if(!is_resource(zip_open($src_file)))
			{
				$src_file=dirname($_SERVER['SCRIPT_FILENAME'])."/".$src_file;
			}

			if (is_resource($zip = zip_open($src_file)))
			{
				$splitter = ($create_zip_name_dir === true) ? "." : "/";
				if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
					
				// Create the directories to the destination dir if they don't already exist
				$this->create_dirs($dest_dir);

				// For every file in the zip-packet
				while ($zip_entry = zip_read($zip))
				{
					// Now we're going to create the directories in the destination directories

					// If the file is not in the root dir
					$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
					if ($pos_last_slash !== false)
					{
						// Create the directory where the zip-entry should be saved (with a "/" at the end)
						$this->create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
					}

					// Open the entry
					if (zip_entry_open($zip,$zip_entry,"r"))
					{
							
						// The name of the file to save on the disk
						$file_name = $dest_dir.zip_entry_name($zip_entry);
						$this->setFile($file_name);
						
						// Check if the files should be overwritten or not
						if ($overwrite === true || $overwrite === false && !is_file($file_name))
						{
							// Get the content of the zip entry
							$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

							if(!is_dir($file_name))
							file_put_contents($file_name, $fstream );
							// Set the rights
							if(file_exists($file_name))
							{
								chmod($file_name, 0777);
								//echo "<br />\n<span style=\"color:#1da319;\">file saved: </span>".$file_name."<br />";
							}
							else
							{
								$this->writeLog("<br />\n<span style=\"color:red;\">file not found: </span>".$file_name."<br />");
								die( "<br />\n<span style=\"color:red;\">file not found: </span>".$file_name."<br />");
							}
						}
							
						// Close the entry
						zip_entry_close($zip_entry);
					}
				}
				// Close the zip-file
				zip_close($zip);
			}
			else
			{
				$this->writeLog("No Zip Archive Found");
				die("No Zip Archive Found.");
				return false;
			}

			return true;
		}
		else
		{
			if(version_compare(phpversion(), "5.2.0", "<"))
			$infoVersion="(use PHP 5.2.0 or later)";
			$this->writeLog("<br />\nYou need to install/enable the php_zip.dll extension $infoVersion");
			die("<br />\nYou need to install/enable the php_zip.dll extension $infoVersion");
		}
	}
    
    	/**
	 * @Todo work only for the windows OS
	 * @param unknown_type $path
	 * @return unknown_type
	 */
	public function create_dirs($path)
	{
		if (!is_dir($path))
		{
			$directory_path = "";
			$directories = explode("/",$path);
			array_pop($directories);

			foreach($directories as $directory)
			{
				$directory_path .= $directory."/";
				if (!is_dir($directory_path))
				{
					mkdir($directory_path);
					chmod($directory_path, 0777);
				}
			}
		}
	}
    
	public function importRow($data)
	{
		array_walk($data, 'trim_data');
		$str = Zend_Json::encode($data);
		$sku = $data[1];
		try {
			$res = $this->con->query("SELECT * FROM $this->table_name WHERE sku = '".$sku."'")->fetchAll();
			if(count($res)>0){
				$id = $res[0]['id'];
				$Array = array(
									':sku'			=>		$sku,
									':str'			=>		$str,
									':estatus'		=>		'0',
									':id'			=>		$id,
				);
				$ret = $this->upStmt->execute($Array);
				return $id;
			}else {
				if($sku != '' && $data[0] != '') {
					$Array = array(
									':sku'			=>		$sku,
									':str'			=>		$str,
									':estatus'		=>		'0',
					);
					$ret = $this->inStmt->execute($Array);
					$id = $this->con->lastInsertId();
					return $id;
				}
			}
		}catch (Exception $e) {
			$msg = $str." - Insert Row Problem: ".$e->getMessage();
			Mage::log($msg, 7, $this->logFile);
			return false;
		}
	}
	public function processFile($file)	{
	     try {
	        if($file!='' &&  file_exists($file)) {
			    $this->inStmt = $this->con->prepare("INSERT INTO $this->table_name
                    ( str, sku, estatus)
                    VALUES (:str, :sku, :estatus ) ");				
				$this->upStmt = $this->con->prepare("UPDATE $this->table_name SET
				  str = :str , sku = :sku , estatus = :estatus
				  WHERE id = :id ");
				$fp = fopen($file, 'r');
				while (!feof($fp))
				{
					$buffer = trim(fgets($fp));
                	if($buffer != '') {
					    $data=explode("\t",$buffer);
                       	$this->importRow($data);
					}
				}
                Mage::log($file." Stored Successfully ! ", 7, $this->logFile);
           	}else {
				Mage::log($file." File not exists ! ", 7, $this->logFile);
			}
		}catch (Exception $e) {
			Mage::log($file." Stored Failure ! ". $e->getMessage(), 7, $this->logFile);
		}
	}
	public function getFiles()
	{
		return implode(",",$this->fileArray);
	}

	public function process()
	{
	    /*$this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/SC4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/SKU4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/SL4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/BROC4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/FF4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/CL4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\SPRPRICE\4Q10_Full_Catalog/DEMOS4QTR.txt';
        */
        $fileName=$this->getConfigVal('ftp_file');
        $this->cleanTempTable();
		foreach($this->fileArray as $key=>$file) {
		    if(basename($file) == $fileName){
		       $this->processFile($file);
            }
		}
   	}
	
	 /** 
     *     Quick Price Updating Start
     **/   
    
    public function getPriceConfigVal($pricefield)
	{
		return Mage::getStoreConfig('managecatalogspr/priceupdate/'.$pricefield);
	}
    
    public function cleanPriceLog($flag=true)
	{
		if(!$this->getPriceConfigVal){
			$this->getPriceConfigVal = true;	
		}
		if($flag) {
			if(file_exists(Mage::getBaseDir('var').DS.'log'.DS.$this->pricelogFile)) {
				unlink(Mage::getBaseDir('var').DS.'log'.DS.$this->pricelogFile);
			}
		}
		$this->logCheck = true;
	}
	
	 public function processPrice()
	{  
	  	$impObj = Mage::getModel('managecatalogspr/Import');
        $fileName=$this->getConfigVal('ftp_file');
	   	foreach($this->fileArray as $key=>$file) {
	   	  if(basename($file) == $fileName){
		       $this->mcId=$impObj->saveQuickPriceEntry(
				array(	'status'=> 0, 
                        'files'=>$file,
		                 ));
			   $this->processFilePrice($file);
		    } 
		}
		$tempPriceResource = Mage::getResourceModel('managecatalogspr/temp_price');
		$tempPriceResource->reindexData();
		
  	}
    
   	public function processFilePrice($file)
    	{
        try {
		  $impObj = Mage::getModel('managecatalogspr/Import');
		  $tempPrice = Mage::getResourceModel('managecatalogspr/temp_price');
        	$tempPrice->loadDataInfile($file);
			Mage::log($file." Import Price Processed Successfully ! " , 7, $this->pricelogFile);
            Mage::log( "total :". $tempPrice->getCountData(), 7, $this->pricelogFile);
			$impObj->saveQuickPriceEntry(
				array(	'total'=> $tempPrice->getCountData(),
						'success'=> $tempPrice->getCountData(),
						'fail'=> 0,
						'status'=> 1, 
                        'content'=>''),$this->mcId);
           	return true;
		} catch (Exception $e) {
			Mage::log($file." Import Price Processed Failure ! ". $e->getMessage(), 7, $this->pricelogFile);
		    Mage::log( "total :". $tempPrice->getCountData(), 7, $this->pricelogFile);
			$impObj->saveQuickPriceEntry(
				array(	'total'=> $tempPrice->getCountData(),
						'success'=> $tempPrice->getCountData(),
						'fail'=> 0,
						'status'=> 3, 
                        'files'=>$file,
					  	'content'=>''));
          	return false;
		}
 	}
	public function getAttrributeId($code)
	{
		if($code) {
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$attributeId = $installer->getAttributeId('catalog_product', $code);
			return $attributeId;
		}else return "";
	}
	public function rebuildPriceIndex()
	{
		// Price index rebuild

		$atr_ids[] = $this->getAttrributeId('price');
		$atr_ids[] = $this->getAttrributeId('cost');
		$this->con->query("TRUNCATE `catalogindex_eav`;");
		$this->con->query("TRUNCATE TABLE `catalogindex_price`;");
		$this->con->query("TRUNCATE `catalogindex_minimal_price`;");
		$this->con->query("TRUNCATE `core_flag`;");


		foreach ($atr_ids as $atr_id) {
			$sql = $this->con->query("INSERT INTO catalogindex_price
			(entity_id,attribute_id, customer_group_id, qty , value,
			tax_class_id,website_id)
			SELECT distinct(entity_id) , ".$atr_id.", 0 , 0.0, value, 2, 1
			FROM catalog_product_entity_decimal
			WHERE attribute_id = '".$atr_id."'");
		}

		/*
		 $indexer = Mage::getSingleton('catalogindex/indexer');
		 $this->_getIndexer()->plainReindex(null,Mage_CatalogIndex_Model_Indexer::REINDEX_TYPE_PRICE);
		 $this->clearPriceAggregation();
		 */
		Mage::log("Price indices rebuild successfully! ", 7, $this->logFile);
	}
	/**
	 * Get indexer object
	 *
	 * @return Mage_CatalogIndex_Model_Indexer
	 */
	protected function _getIndexer()
	{
		return Mage::getSingleton('catalogindex/indexer');
	}

	/**
	 * Get aggregation object
	 *
	 * @return Mage_CatalogIndex_Model_Aggregation
	 */
	protected function _getAggregator()
	{
		return Mage::getSingleton('catalogindex/aggregation');
	}

	/**
	 * Delete price aggreagation data
	 *
	 * @return Mage_CatalogIndex_Model_Observer
	 */
	public function clearPriceAggregation()
	{
		$this->_getAggregator()->clearCacheData(array(
		Mage_Catalog_Model_Product_Type_Price::CACHE_TAG
		));
		return $this;
	}
	public function refreshAllCache()
	{
		umask(0);
		Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
		flush();
		Mage::app()->cleanCache();
		Mage::log("Overall Cache is Cleaned! ", 7, $this->logFile);

		//rebuild Price indices.
		$this->rebuildPriceIndex();

		flush();
		Mage::getModel('catalog/url')->refreshRewrites();
		Mage::log("Catalog Rewrites was refreshed succesfuly! ", 7, $this->logFile);


		//		flush();
		//		Mage::getModel('catalog/product_image')->clearCache();
		//		Mage::log("Image cache was cleared succesfuly! ", 7, $this->logFile);

		//		flush();
		//		Mage::getSingleton('catalogindex/indexer')->plainReindex();
		//		Mage::log("Layered Navigation Indices was refreshed succesfuly! ", 7, $this->logFile);
		//

		flush();
		Mage::getModel('catalogsearch/fulltext')->rebuildIndex();
		Mage::log('Search index was rebuilt succesfully!', 7, $this->logFile);

		//
		//		flush();
		//		Mage::getResourceSingleton('catalog/category_flat')->rebuild();
		//		Mage::log('Flat category was rebuilt successfully!',  7, $this->logFile);

		//		flush();
		//		Mage::getResourceSingleton('catalog/product_flat_indexer')->rebuild();
		//		Mage::log('flat product was rebuilt successfully',  7, $this->logFile);
		//
		//		flush();
	}
	public function sendStatus()
	{
		system('zip -r '.Maven_ManageCatalog_Model_Setting::getImportPath(Maven_ManageCatalog_Model_Setting::PRICE_FOLDER).'price_log.zip '.Mage::getBaseDir('var').DS.'log'.DS.$this->logFile);
		$link = Maven_ManageCatalog_Model_Setting::getImportUrl(Maven_ManageCatalog_Model_Setting::PRICE_FOLDER).'price_log.zip';

		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

		// Additional headers
		$headers .= 'To: Flatrox Price import '.Mage::getStoreConfig('managecatalog/general/email') . "\r\n";
		$headers .= 'From: system <system@flatrox.com>' . "\r\n";
		$headers .= 'Cc: '.Mage::getStoreConfig('managecatalog/general/ccemail') . "\r\n";

		$message = "Price Import data stored in system";
        $result=$this->getLastManageCatalogData();
        $message.="<BR/> Total   :".$result['total'];
        $message.="<BR/> Success :".$result['success'];
        $message.="<BR/> Fail    :".$result['fail'];
      
		@mail(Mage::getStoreConfig('managecatalogspr/general/email'), "Product Import Log", nl2br($message), $headers);
	}
    public function getLastManageCatalogData()
	{
		$cols = Mage::getResourceModel('managecatalogspr/managecatalog')->getLast('Price');
        if(isset($cols['managecatalog_id'])) {
		  	return $cols;
		}
	}
}

// Global And trace function ..............
function trim_data(&$item1, $key)
{
	$item1 = trim($item1);
	$item1 = trim($item1,'"');
}
function final_escape(&$item1)
{
	if(!is_array($item1)) {
		$item1 = htmlentities($item1 , ENT_QUOTES, "utf-8" );
		//$item1 = mysql_escape_string((string) trim($item1));
	}
}

